package me.macd.mindoc.controller;

import me.macd.mindoc.dto.Result;
import me.macd.mindoc.model.Members;
import me.macd.mindoc.util.constants.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @program: mindoc
 * @description: ${description}
 * @author: 2018-09-19
 * @create: 2018-09-19 14:34
 */
@Controller
public class AccountController {

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model) {
        //model.addAttribute("time", new Date(System.currentTimeMillis()));
        Subject subject = SecurityUtils.getSubject();

        if (subject.isAuthenticated()) {
            // 登录过了跳转首页
        }

        return "account/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Result login(@RequestParam("account") String account,
                        @RequestParam("password") String password,
                        @RequestParam(value = "is_remember", required = false) String isRemember) {
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(account, password);

        try {
            subject.login(token);

            //将登录的对象放入到Session中
            //Session session = subject.getSession();
            return new Result(0, "ok", "");
        } catch (LockedAccountException ex) {
            return new Result(500, "账号已锁定", null);
        } catch (UnknownAccountException ex) {
            return new Result(500, "账号或密码错误", null);
        } catch (AuthenticationException ex) {
            return new Result(500, "账号或密码错误", null);
        } catch (Exception ex) {
            return new Result(500, "账号或密码错误", null);
        }
    }
}
